import * as L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import '@geoman-io/leaflet-geoman-free';
import '@geoman-io/leaflet-geoman-free/dist/leaflet-geoman.css';
import 'leaflet.polyline.snakeanim';
import 'leaflet-responsive-popup'
// import * as positionDiaLogInstance from '../../components/RW/positionDialog/index';
import * as propertyShowTips from './components/propertyShowTips/index';
// import 'leaflet-responsive-popup'
import { getToken } from '../auth';
import Offline from '@/assets/loginmini/icon/bintl1.png';
import selectSuccess from '@/assets/loginmini/icon/icon-success.png';
import Leave from '@/assets/loginmini/icon/bintl2.png';
import Moving from '@/assets/loginmini/icon/bintl3.png';
import Lying from '@/assets/loginmini/icon/bintl4.png';
import positinIcon from '@/assets/svg/positon.svg'
import { cameraList } from '@/api/base/device/camera.ts'
import Camera from '@/assets/images/video.png'
import v_dialog from "@/components/rw/videoDialog/index.js";
import { useMessage } from '@/hooks/web/useMessage';
const { createMessage: msg } = useMessage();
// import { bedpositionDialogInstance, setUserInfo, positionDialogInit } from '../../components/RW/bedDialog';
import { unref } from 'vue';
const windowInstance: any = window;
const token: any = getToken();
let polyline = null;
let polylineAll: any = [];
const mapOptions: IMapOptions = {
  zoomControl: true, //禁用 + - 按钮
  doubleClickZoom: false, // 禁用双击放大
  attributionControl: false, // 显示右下角leaflet标识
  minZoom: -3,
  maxZoom: 5,
  center: [0, 0],
  zoom: 0,
  crs: L.CRS.Simple,
  zoomSnap: 0.1,
  zoomDelta: 0.3,
};
class Map implements IMap {
  leafletMap = null as any;
  tags = {};
  mapObj = {} as IMapobj;
  polygon = null;
  selectedId = '';
  nowIndex = 0;
  playIndex = 1;
  filterCode = '';
  positionType = '';
  markerList = [];
  cameras = [];
  polygonList = {};
  options = {}
  savedZoom = 0;
  savedCenter = [0, 0];
  nowPlayPolygonList = [];
  devicesCallback = null;
  positionDiaLog = null as any;
  assetsDialog = null;
  isActive = false;
  isPlay = true;
  snakingSpeed = 200;
  showPositionDiaLog = false;
  featureGroup = null;
  polylineAll = []
  warningTag = {} as any;
  ployLine = null
  historyIcon = null;
  v_dialogs = [];
  nowVideoSet = new Set()
  real_polyline = null
  constructor(el: string, options: Record<string, any> = {}) {
    this.options = options
    this.init(el, options);
  }
  /**
   * @param 初始化leaflet
   * @returns leafletMap
   */
  init(el: string, options?: Record<string, any>): any {
    if (!el) return;
    const _this = this;
    this.leafletMap = L.map(el, {
      ...mapOptions,
      ...options,
    });


    this.positionType = options.type;
    this.leafletMap.on('movestart', () => (_this.isActive = true));
    this.leafletMap.on('moveend', () => (_this.isActive = false));
    this.leafletMap.on('zoomstart', () => (_this.isActive = true));
    this.leafletMap.on('zoomend', () => (_this.isActive = false));
    this.leafletMap.on('zoomend', () => (_this.isActive = false));

    if (options.offLine) {
      this.leafletMap.setView([31.128150939941406, 121.60834503173828], 13);
      let titleLayerUrl = windowInstance.config.mapOnline ? 'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}' : windowInstance.config.mapServerdomain + '/{z}/{x}/{y}.png'
      L.tileLayer(titleLayerUrl, {
        minZoom: 10, // 最小缩放级别※
        maxZoom: 18, // 最大缩放级别※
        type: 'map'
      }).addTo(this.leafletMap)

    }
    return this.leafletMap;
  }
  /**
   * @param 加载地图
   * @returns void
   */
  loadMap(obj: IMapobj) {
    const _this = this;
    return new Promise((resolve, reject) => {
      _this.mapObj = obj;
      var imgUrl = _this.mapObj.imageFullUrl;
      // 切换地图的时候把之前的标签数组清空
      var imageObj = new Image();
      imageObj.src = imgUrl;
      imageObj.onload = function () {
        //删除图层所有控件
        _this.leafletMap.eachLayer(function (layer) {
          _this.leafletMap.removeLayer(layer);
        });
        /* 删除固定资产和人员的定位makers*/
        // positionDiaLogInstance.positionDiaLogRemove();
        propertyShowTips.positionDiaLogRemove();
        _this.tags = {};
        let w = imageObj.width,
          h = imageObj.height;
        let bounds = [
          [h, w],
          [0, 0],
        ];
        let imageOverlay = L.imageOverlay(imgUrl, bounds).addTo(_this.leafletMap);
        imageOverlay.on('load', function () {
          _this.leafletMap.fitBounds(bounds);
        });
        _this.mapObj.width = imageObj.width;
        _this.mapObj.height = imageObj.height;
        if (_this.options.showCamera) {
          _this.loadCamera()
        }
        resolve({ mapObj: _this.mapObj, leafletMap: _this.leafletMap });
      };
      imageObj.onerror = (e) => {
        reject(e);
      };
    });
  }
  /**
   * @param 定位方法
   * @returns void
   */
  position(data) {
    const _this = this;
    const windowInstance: any = window;
    if (!data.length) {
      for (let key in _this.tags) {
        _this.tags[key].leafletTag.remove()
      }
      _this.tags = {}
    }

    for (let key in this.tags) {
      let item = this.tags[key]
      item.isPosition = false
    }

    if (_this.isActive) {
      return;
    }

    let showWarnTag = (warningRes) => {
      if (_this.warningTag.leafletLayer) {
        _this.warningTag.leafletLayerNaNpxove();
      }
      // warningTag =allWarningTags.find(x => x.tagCode == warningRes.tagCode) || {};
      _this.warningTag = warningRes;
      if (_this.warningTag.binderCategory == "Bed") {
        return
      }
      if (!_this.warningTag.deviceCode) {
        return;
      }
      var myIcons = L.divIcon({
        iconSize: [20, 20],
        iconAnchor: [15, 10],
        className: `marker_icon ` + warningRes.deviceCode,
        html: `
            <div  class="animate-wave-content">
            <img class="member_icon" src="${windowInstance.config.base_url + warningRes.iconUrl}"/>
            <div class="animate-wave">
                    <div class="w1"></div>
                    <div class="w2"></div>
                    <div class="w3"></div>
                    <div class="w4"></div>
                    <div class="w5"></div>
                    <div class="w6"></div>
            </div></div>`,
      })
      warningRes.isActive = true
      _this.warningTag.leafletTag.setIcon(myIcons)
    };
    for (let i = 0; i < data.length; i++) {
      let obj = data[i];
      obj.deviceCode = obj.deviceCode || obj.memberCode;
      if (_this.mapObj.id != obj.mapId) {
        continue;
      }
      const objt = {
        Moving,
        Offline,
        Leave,
        Lying,
      };
      var myIcon = L.icon({
        iconUrl: objt[obj.status] || windowInstance.config.base_url + obj.iconUrl,
        iconSize: [20, 20],
        iconAnchor: [10, 10],
        className: `marker_icon ` + obj.deviceCode,
      });
      // 雷达图标
      let envirIcon = L.divIcon({
        html: `<div class='leaflet_bed_text'><p class="${obj.isWarning ? 'error ld' : 'ld'}">${obj.status || ''}</p> </div>`,
        iconAnchor: [-15, 12],
      });
      // 床垫图标
      // 先去marker列表里看看能不能找到相同的，如果找到相同的就更新位置 否则就新增
      let r = _this.tags[obj.deviceCode];
      if (r) {
        obj = { ...r, ...obj }
        _this.tags[obj.deviceCode].isPosition = true;
        // 找到了 就更新位置
        _this.tags[obj.deviceCode].leafletTag.setLatLng([obj.posY, obj.posX]);
        if (obj.isWarning && !_this.tags[obj.deviceCode].isActive) {
          showWarnTag(_this.tags[obj.deviceCode]);
        } else if (!obj.isWarning && _this.tags[obj.deviceCode].isActive) {
          _this.tags[obj.deviceCode].leafletTag.setIcon(myIcon);
          _this.tags[obj.deviceCode].isActive = false;
        }
        _this.tags[obj.deviceCode].bedMarker && _this.tags[obj.deviceCode].bedMarker.setUserInfo(obj);
        _this.tags[obj.deviceCode].envirMarker && _this.tags[obj.deviceCode].envirMarker.setIcon(myIcon);
      } else {
        // 没找到 创建

        let leafletTag = L.marker([obj.posY, obj.posX], {
          className: obj.deviceCode,
          radius: 10,
          fillColor: 'red',
          fillOpacity: 1,
          weight: 1,
          icon: myIcon,
          options: obj,
        }).addTo(_this.leafletMap);
        const typesObj = {
          Asset: "memberCode",
          MedicalCare: "memberName"
        }
        // let toolTipContent = obj.binderCategory === 'Asset' ? obj.memberCode : (`${obj.expandAttr?.bedName || obj.deviceCode || '-'}`);
        let toolTipContent = typesObj[obj.binderCategory] ? obj[typesObj[obj.binderCategory]] : (`${obj.expandAttr?.bedName || obj.binderName || '-'}`);
        // let toolTipContent = obj.binderName
        let t = document.createElement('div');
        t.innerHTML = toolTipContent;
        leafletTag.setTooltipContent(t);
        leafletTag.bindTooltip(t, { permanent: true, offset: L.point(0, -10), direction: 'top', className: `tag_info_tooltip tag-${obj.deviceCode}` }).openTooltip();
        if (this.positionType === 'monitor') {
          leafletTag.addEventListener('click', (e) => {
            this.addToopDiaLog(e, leafletTag.getLatLng());
          });
          //固定资产和移动资产
        } else if (this.positionType === 'monitor' && (obj.binderCategory === 'FixAsset' || obj.binderCategory === 'Asset')) {
          leafletTag.addEventListener('click', (e) => {
            // this.addToopDiaLog(e);
            this.addToopDialopFixAsset(e);
          });
          //固定资产和移动资产
        }
        // else if (this.positionType === 'monitor') {
        //   leafletTag.addEventListener('click', (e) => {
        //     this.addToopDialopFixAsset(e);
        //   });
        // }
        obj.leafletTag = leafletTag;
        _this.reflushDevices();

        // 创建床垫状态显示信息
        if (obj.binderCategory === 'Bed' && obj.status) {
          obj.leafletTag.closeTooltip();
        }
        // 创建雷达状态显示信息
        if (obj.binderCategory === 'Envir') {
          obj.envirMarker = L.marker([obj.posY, obj.posX], { icon: envirIcon }).addTo(this.leafletMap);
          obj.leafletTag.closeTooltip();
        }
        obj.isPosition = true;
        _this.tags[obj.deviceCode] = obj;
      }
    }
    _this.filterItem();

  }
  binderDialog() {
    this.positionDiaLog = L.responsivePopup({
      offset: [0, 30],
      className: 'position_dialog',
      autoPan: false,
      keepInView: true,
    });
  }
  cameraRemove() {
    this.cameras.forEach(x => {
      x.remove && x.remove()
    })
  }
  loadCamera() {
    this.cameraRemove()
    cameraList({ MapId: this.mapObj.id, DeviceCategory: "DEVICE_CATEGORY_CAMERA" }).then(res => {
      let cameraList = res.data
      if (!cameraList) return

      loadCameraMarker(cameraList)
    })



    let loadCameraMarker = (list) => {
      for (let i = 0; i < list.length; i++) {
        let item = list[i]

        if (!item.coordinate) continue;

        var myIcon = L.icon({
          iconUrl: Camera,
          iconSize: [20, 20],
          iconAnchor: [10, 10],
          className: `marker_icon ` + item.deviceCode,
        });
        let leafletTag = L.marker(item.coordinate?.split(","), {
          className: item.deviceCode,
          radius: 10,
          fillColor: 'red',
          fillOpacity: 1,
          weight: 1,
          icon: myIcon,
          options: item,
        }).addTo(this.leafletMap);

        leafletTag.on('click', e => {
          this.showAreaVideo({ areafidList: `Camera/Play?id=${item.deviceId}`, areaName: item.areaName, deviceId: item.deviceId })
        })

        this.cameras.push(leafletTag)
      }
    }
  }
  showAreaVideo(data) {
    if (!data.areafidList) {
      return;
    }

    let v_dialogs = v_dialog.newInstance({ deviceId: data.deviceId });

    if (!v_dialogs) return msg.error("无法播放")

    v_dialogs.diagram.init(data);
  }
  closeInstaceVideo() {
    this.v_dialogs.forEach((x: any) => {
      x.closeAll()
      this.nowVideoSet.clear()
    })
    this.v_dialogs = []
  }
  addToopDiaLog(e, latLng) {
    // 存储原始的地图中心点和缩放级别
    const originalCenter = this.leafletMap.getCenter();
    const originalZoom = this.leafletMap.getZoom();

    let options = e?.target?.options?.options || e.options;
    this.positionDiaLog = L.responsivePopup({
      offset: [0, 30],
      className: 'position_dialog-assets',
      autoPan: false,
      keepInView: true,
    });

    if (!this.showPositionDiaLog) {
      this.positionDiaLog.setContent(propertyShowTips.dislogEl.$el);
      // this.positionDiaLog.setContent('这是一个弹出面板<br>可以设置宽度和高度');
    }
    // setTimeout(() => {
    this.positionDiaLog.setLatLng(latLng);
    // setTimeout(() => {
    //   this.positionDiaLog.setLatLng(latlng);
    // }, 1000)

    // propertyShowTips.setBedList({ mapId: this.mapObj.id, categorys: 'FixAsset' });
    propertyShowTips.setUserInfo(
      options,
      this.positionDeivce.bind(this, "")
    );
    this.positionDiaLog.openOn(this.leafletMap);
    // }, 1000);


    this.positionDiaLog.addEventListener('remove', () => {
      // 关闭位置对话框
      // positionDiaLogInstance.closePositionDialog();
      // 将地图重置到原始位置
      this.leafletMap.setView(originalCenter, originalZoom);
    });
  }
  openDialog(obj) {
    const _this = this;
    const targetElement = document.getElementsByClassName("tag-" + _this.tags[obj.deviceCode]?.deviceCode)[0];
    const elements = document.querySelectorAll('.leaflet-tooltip');
    elements.forEach(el => {
      el.classList.remove('activeClass')
    });
    targetElement.classList.add('activeClass');
    // const getLatLng = _this.tags[obj.deviceCode].leafletTag.getLatLng()
    // _this.tags[obj.deviceCode].leafletTag.openTooltip(getLatLng)
    // _this.addToopDiaLog(_this.tags[obj.deviceCode].leafletTag.options)

  }
  /* 固定资产的鼠标划入的样式*/
  addToopDialopFixAsset(e) {
    // 存储原始的地图中心点和缩放级别
    const originalCenter = this.leafletMap.getCenter();
    const originalZoom = this.leafletMap.getZoom();

    let options = e.target.options.options;
    this.assetsDialog = L.responsivePopup({
      offset: [0, 30],
      className: 'position_dialog-assets',
      autoPan: false,
      keepInView: true,
    });
    if (!this.showPositionDiaLog) {
      this.assetsDialog.setContent(propertyShowTips.dislogEl.$el);
    }
    this.assetsDialog.setLatLng(e.latlng);
    const param = {
      binderName: options.binderName,
      binderTypeName: options.binderTypeName,
      binderCode: options.binderCode,
      mapName: options.mapName,
      areaName: options.areaName,
      isWarning: options.isWarning,
      departmentName: options.departmentName,
      binderImage: options.binderImage,
      image: options.image,
      organizationName: options.organizationName,
      belongMapName: options.belongMapName,
      belongAreaName: options.belongMapName,
      // binderName:options.binderName,
      // binderName:options.binderName,
      // binderName:options.binderName,
    }
    // propertyShowTips.setBedList({ mapId: this.mapObj.id, categorys: 'FixAsset' });
    // { Keyword: options.memberId, mapIds: options.memberId, name: options.name, assetType: options.assetTypeStr, deptName: options.deptName, code: options.code, userTypeIconUrl: windowInstance.config.base_url + options.userTypeIconUrl }
    propertyShowTips.setUserInfo(
      param,
      this.positionDeivce.bind(this, "")
    );

    this.assetsDialog.openOn(this.leafletMap);

    this.assetsDialog.addEventListener('remove', () => {
      // 关闭位置对话框
      propertyShowTips.closePositionDialog();
      // 将地图重置到原始位置
      this.leafletMap.setView(originalCenter, originalZoom);
    });
  }
  positionDeivce(options) {
    let arr = this.getPositionTags();
    options = unref(options);
    let r = arr.find((item) => {
      return item.expandAttr.bedId == options.bedId;
    });
    if (!r) return;
    let device = this.tags[r.deviceCode];
    if (device) {
      // positionDiaLogInstance.setUserInfo(null, this.positionDeivce.bind(this));
      this.positionDiaLog.setLatLng(device.leafletTag.getLatLng());
    }
  }
  getPositionTags() {
    let arr = [];
    for (let key in this.tags) {
      if (this.tags[key].binderCategory === 'InPatient') {
        arr.push(this.tags[key]);
      }
    }
    return arr;
  }
  /*
    历史轨迹删除所有绘制的线条
  */
  removeHistoryLine() {
    if (this.historyIcon && this.leafletMap) this.leafletMap.removeLayer(this.historyIcon)
    if (this.real_polyline && this.leafletMap) this.leafletMap.removeLayer(this.real_polyline);
    this.real_polyline = null;
  }
  /**
  *
  * @param points 历史轨迹点
  * @returns voids
  * @description 绘画历史轨迹
  */

  setHistoryLine(data) {
    if (!data.length) return;
    const _this = this;
    let nowPlayIndex = 0;
    // 根据地图id分割成二维数组
    const splitArraysByMapId = (datas) => {
      const resultArrays = [];
      let currentArray = [];
      for (let i = 0, length = datas.length; i < length; i++) {
        if (i === 0 || datas[i].mapId !== datas[i - 1].mapId) {
          if (currentArray.length > 0) {
            resultArrays.push(currentArray);
          }
          currentArray = [];
        }
        currentArray.push(datas[i]);
      }

      if (currentArray.length > 0) {
        resultArrays.push(currentArray);
      }
      return resultArrays;
    };
    let myIcons = L.icon({
      iconSize: [40, 40],
      iconAnchor: [15, 10],
      className: `marker_icon `,
      iconUrl: positinIcon,
    })
    const resultArrays = splitArraysByMapId(data);
    let loadNextMap = () => {
      if (nowPlayIndex < resultArrays.length - 1) {
        nowPlayIndex++;
        showMarkerLine(resultArrays[nowPlayIndex]);
      }
    };
    // 播放轨迹
    let showMarkerLine = async (datas: ITag[]) => {
      let firstObj = datas[0];
      await this.loadMapFunc(firstObj);

      const uniquePoints = [];

      // 遍历所有点，去除相邻的重复点
      for (let i = 0; i < datas.length; i++) {
        const item = datas[i];
        const currentLatLng = L.latLng(item.posY, item.posX);

        // 添加第一个点
        if (i === 0) {
          uniquePoints.push(currentLatLng);
        } else {
          const previousLatLng = uniquePoints[uniquePoints.length - 1];

          // 检查当前点和上一个点是否相同
          if (currentLatLng.lat !== previousLatLng.lat || currentLatLng.lng !== previousLatLng.lng) {
            uniquePoints.push(currentLatLng);
          }
        }
      }

      // 如果需要将结果映射为 LatLng 对象
      const latLngPoints = uniquePoints.map(latLng => L.latLng(latLng.lat, latLng.lng));


      if (latLngPoints.length == 1) {
        try {
          L.circleMarker(latLngPoints[0], {
            radius: 5,
            fillColor: 'red',
            fillOpacity: 1,
            weight: 1,
          }).addTo(_this.leafletMap);
          setTimeout(() => {
            loadNextMap();
          }, 2000);
        } catch {
          loadNextMap();
        }
        return;
      }
      _this.ployLine = L.polyline(latLngPoints, { color: 'red', opacity: 0.6, snakingSpeed: _this.snakingSpeed }).addTo(_this.leafletMap);

      _this.ployLine.on('snakeend', (e) => {
        this.historyIcon = L.marker(latLngPoints[latLngPoints.length - 1], { icon: myIcons }).addTo(_this.leafletMap);
        loadNextMap();
      });
      try {
        _this.ployLine.snakeIn();
      } catch {
        loadNextMap();
      }
    };

    // 默认执行一次
    showMarkerLine(resultArrays[nowPlayIndex]);
  }

  setLineStep(step) {
    if (!this.ployLine) return
    this.snakingSpeed = step
    this.ployLine.options.snakingSpeed = step
    this.historyIcon && this.historyIcon.remove()
    this.ployLine.snakeIn(step)
  }



  getRandomColor() {
    var characters = '0123456789ABCDEF';
    var color = '#';

    for (var i = 0; i < 6; i++) {
      color += characters[Math.floor(Math.random() * 16)];
    }

    return color;
  }
  setLineSteps(step) {
    if (!this.polylineAll) return
    this.polylineAll.forEach(x => {
      x.options.snakingSpeed = step
      setTimeout(() => {
        x.snakeIn(step)
      }, 500)
    })

  }
  async setHistoryLines(datas, mapId) {
    const _this = this
    if (!datas.length) return

    this.polylineAll.forEach(x => {
      x.remove()
    })

    this.polylineAll = []


    await this.loadMapFunc({ mapId, mapCode: mapId });

    for (let i = 0; i < datas.length; i++) {
      let obj = datas[i]

      if (!obj.histories.length) continue;


      const uniquePoints = [];

      // 遍历所有点，去除相邻的重复点
      for (let i = 0; i < obj.histories.length; i++) {
        const item = obj.histories[i];
        const currentLatLng = L.latLng(item.posY, item.posX);

        // 添加第一个点
        if (i === 0) {
          uniquePoints.push(currentLatLng);
        } else {
          const previousLatLng = uniquePoints[uniquePoints.length - 1];

          // 检查当前点和上一个点是否相同
          if (currentLatLng.lat !== previousLatLng.lat || currentLatLng.lng !== previousLatLng.lng) {
            uniquePoints.push(currentLatLng);
          }
        }
      }

      // 如果需要将结果映射为 LatLng 对象
      const latLngPoints = uniquePoints.map(latLng => L.latLng(latLng.lat, latLng.lng));


      const binderName = obj.bindName
      var myIcon = L.icon({
        iconUrl: windowInstance.config.base_url + obj.binderImage,
        iconSize: [20, 20],
        iconAnchor: [10, 10],
        className: `marker_icon ` + obj.histories[0].deviceCode,
      });
      //  <img class="member_icon" src="${windowInstance.config.base_url + obj.iconUrl}"/>
      let historyMarkerLayer = L.marker(L.latLng(obj.histories[0].posY, obj.histories[0].posX), {
        className: obj.histories[0].deviceCode,
        radius: 10,
        fillColor: 'red',
        fillOpacity: 1,
        weight: 1,
        icon: myIcon,
        options: obj,
      }).addTo(_this.leafletMap);

      let t = document.createElement('div');
      t.innerHTML = binderName;
      historyMarkerLayer.setTooltipContent(t);
      historyMarkerLayer.bindTooltip(t, { permanent: true, offset: L.point(0, -10), direction: 'top', className: `tag_info_tooltip tag-${obj.deviceCode}` }).openTooltip();

      let pl = polyline = L.polyline(latLngPoints, { color: this.getRandomColor(), opacity: 0.6 }).addTo(_this.leafletMap);

      pl.on('snake', (e) => {
        historyMarkerLayer.setLatLng(
          e.target.getLatLngs()[0][e.target.getLatLngs()[0].length - 1]
        )
      })


      pl.snakeIn();

      this.polylineAll.push(pl)

    }

  }
  async setRealLine(data) {
    if (!data.length) return;
    const points = data.map((item) => {
      return [item.posY, item.posX,]
    })
    if (this.mapObj.id && data[0].mapId !== this.mapObj.id) {
      await this.loadMapFunc({ mapId: data[0].mapId, mapCode: data[0].mapCode });
      this.real_polyline && this.real_polyline.remove()
      this.real_polyline = null;
      this.real_polyline = L.polyline([], { color: 'red' }).addTo(this.leafletMap);
    }
    if (this.real_polyline) {
      this.real_polyline.addLatLng(
        points[0]
      );
      // this.real_polyline.redraw()
    } else {
      // // 从LatLng点的数组中创建一条红色的折线
      let points = [
        [200.51, 300.68],
        [300, 400],
        [200.04, 200.2]
      ].map((item) => {
        var l = L.latLng(item[0], item[1])
        return l
      });
      this.real_polyline = L.polyline([], { color: 'red' }).addTo(this.leafletMap);
    }
  }
  loadAre(data) {
    const _this = this
    for (let i = 0; i < data.length; i++) {
      let item = data[i]
      var bounds = item.points.map((item: any) => {
        return [item.y, item.x];
      });
      let polygon = L.polygon(bounds, { color: 'red', zIndex: 999 }).addTo(_this.leafletMap);
      polygon.bindTooltip(item.name)
    }
  }
  /**
   *
   * @param points 区域轨迹点
   * @returns voids
   * @description 加载区域
   */

  loadArea(data: [], FeedData: [], callBack) {
    const _this = this;
    setTimeout(() => {
      this.drawlines(data, callBack, FeedData)
      // this.feedBackLine(FeedData)
    }, 500);
  }
  feedBackLine(FeedData, id) {
    if (!FeedData) return false;
    for (let item of FeedData) {
      if (item.locationId == id || item.id == id) {
        return true
      }
    }
  }
  /**
  * @param 根据中台返回的数据绘制每个区域的位置
  * @returns void
  */
  drawlines(data, callBack, FeedData) {
    const _this = this;
    let myIcons = L.icon({
      iconSize: [40, 40],
      iconAnchor: [15, 10],
      className: `marker_icon `,
      iconUrl: selectSuccess,
    })
    for (let item of data) {
      let bounds = item.points.map((item: any) => {
        return [item.y, item.x];
      });
      let polygon = L.polygon(bounds, { color: 'red', zIndex: 999 }).addTo(_this.leafletMap);
      //给已经选中的区域添加标记
      // if (item.selectStatus) {
      //   L.marker(polygon.getCenter(), { icon: myIcons }).addTo(_this.leafletMap)
      // }

      polygon.bindTooltip(item.name, {
        className: item.deviceCode
      })
      polygon.on('mouseover', (e) => {
        polygon.openTooltip(e.latlng)
      })
      if (!callBack) continue;
      let selectMraker;
      const flag = this.feedBackLine(FeedData, item.id);
      if (flag) {
        item.selectStatus = true
        selectMraker = L.marker(polygon.getCenter(), { icon: myIcons }).addTo(_this.leafletMap);
      }
      polygon.on('click', (e) => {
        //在图层上面添加图片
        if (item.selectStatus) {
          selectMraker.remove()
          selectMraker = null;
          item.selectStatus = false
        } else {
          selectMraker = L.marker(polygon.getCenter(), { icon: myIcons }).addTo(_this.leafletMap);
          item.selectStatus = true
        }
        callBack(data, item)
      })
      polygon.on('bindTooltip', (e) => {
      })
    }
  }
  /**
   * @param 设置选中标签
   * @returns void
   */
  setselectedId(id) {
    this.selectedId = id;
  }
  /**
   * @param 设置刷新标签
   * @returns void
   */
  reflushDevices() { }
  /**
   * @param 过滤标签
   * @returns void
   */
  filterItem() {
    for (let key in this.tags) {
      let item = this.tags[key]
      if (!item.isPosition) {
        item.leafletTag && item.leafletTag.remove()
        delete this.tags[key]
      }
    }
  }
  /**
   * @param 加载地图
   * @returns void
   */
  async loadMapFunc(obj) {
    await this.loadMap({
      imageFullUrl: `${windowInstance.config.base_url}Maps/pic/${obj.mapId}?access_token=${token}`,
      width: 50,
      height: 50,
      code: obj.mapCode,
      id: obj.id || obj.mapId
    });
  }
  /**
   * @param 重置
   * @returns void
   */
  close() {
    // positionDiaLogInstance.positionDiaLogRemove();
    propertyShowTips.positionDiaLogRemove();
  }
  removeLayer() {
    for (let key in this.tags) {
      this.tags[key].leafletTag && this.tags[key].leafletTag.remove()
    }
    this.tags = {}
  }
}

export default Map;